<template>
  <div class="contract-create-container">
    <div class="header">
      <h2>创建合同</h2>
      <p class="text-muted">当前项目经理：{{ currentManagerName }}</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 合同创建表单 -->
    <div v-if="!loading" class="card">
      <div class="card-body">
        <form @submit.prevent="createContract">
          <div class="form-group">
            <label for="contractName">合同名称:</label>
            <input
                id="contractName"
                v-model="contract.name"
                type="text"
                class="form-control"
                placeholder="请输入合同名称"
                required
            >
          </div>

          <div class="form-group">
            <label for="customerSelect">客户公司:</label>
            <select
                id="customerSelect"
                v-model="contract.customer"
                class="form-control"
                required
            >
              <option value="" disabled>请选择客户公司</option>
              <option
                  v-for="customer in customers"
                  :key="customer.id"
                  :value="customer"
              >{{ customer.companyName }}</option>
            </select>
          </div>

          <button
              type="submit"
              class="btn btn-primary btn-block"
              :disabled="isSubmitting"
          >
            <i class="fa fa-save mr-2"></i>创建合同
          </button>
        </form>
      </div>
    </div>

    <!-- 合同创建成功后显示 -->
    <div v-if="contractId && !loading" class="card mt-4">
      <div class="card-header">
        <h3>合同创建成功</h3>
      </div>
      <div class="card-body text-center">
        <p class="success-message">
          <i class="fa fa-check-circle mr-2"></i>合同 "{{ contract.name }}" 已成功创建
        </p>
        <button
            @click="goToEditContract"
            class="btn btn-primary mt-4"
        >
          <i class="fa fa-edit mr-2"></i>编辑合同
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ContractCreate',
  data() {
    return {
      contract: {
        name: '',
        projectManager: null,
        customer: null,
        status: 'DRAFT',
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString()
      },
      contractId: null,
      errorMessage: '',
      customers: [],
      loading: true,
      isSubmitting: false
    }
  },
  computed: {
    currentManagerName() {
      return this.$store.state.user?.name || '未登录'
    }
  },
  created() {
    console.log('ContractCreate组件初始化')
    this.checkUserRole()
    this.initializeProjectManager()
    this.fetchCustomers()
  },
  methods: {
    checkUserRole() {
      if (this.$store.state.user && this.$store.state.user.position !== 'PROJECT_MANAGER') {
        console.log('非项目经理，重定向到仪表盘')
        this.$router.push('/employee/dashboard')
      }
    },

    initializeProjectManager() {
      const user = this.$store.state.user
      if (user) {
        this.contract.projectManager = { id: user.id }
        console.log('已自动设置项目经理ID:', user.id)
      } else {
        this.errorMessage = '用户未登录，请重新登录'
        setTimeout(() => {
          this.$router.push('/login')
        }, 2000)
      }
    },

    fetchCustomers() {
      console.log('开始获取客户列表')
      axios.get('/auth/customers')
          .then(response => {
            console.log('获取客户列表成功', response.data)
            this.customers = response.data
          })
          .catch((err) => {
            console.error('获取客户列表错误:', err)
            this.errorMessage = '获取客户列表失败，请检查网络连接'
          })
          .finally(() => {
            this.loading = false
          })
    },

    createContract() {
      if (!this.contract.name || !this.contract.customer) {
        this.errorMessage = '请填写所有必填字段'
        return
      }

      this.isSubmitting = true
      this.errorMessage = ''

      const contractData = {
        name: this.contract.name,
        status: this.contract.status,
        createTime: this.contract.createTime,
        updateTime: this.contract.updateTime,
        projectManager: { id: this.contract.projectManager.id },
        customer: { id: this.contract.customer.id }
      }

      console.log('开始创建合同', contractData)

      axios.post('/auth/contracts', contractData)
          .then(response => {
            console.log('合同创建成功', response.data)
            this.contractId = response.data.id
            this.contract.name = response.data.name // 更新合同名称
            this.showSuccessMessage('合同创建成功')
          })
          .catch((err) => {
            console.error('合同创建失败', err)
            this.errorMessage = err.response?.data?.message || '创建合同失败，请联系管理员'
          })
          .finally(() => {
            this.isSubmitting = false
          })
    },

    goToEditContract() {
      if (this.contractId) {
        this.$router.push({
          name: 'ContractEdit',
          params: { contractId: this.contractId }
        })
      } else {
        this.errorMessage = '合同ID不存在，无法编辑'
      }
    },

    showSuccessMessage(message) {
      console.log(message)
      this.errorMessage = message
      setTimeout(() => {
        this.errorMessage = ''
      }, 3000)
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.contract-create-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.text-muted {
  color: #6c757d;
  font-size: 0.9rem;
  margin-top: 5px;
}

.card {
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.card-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  font-weight: 500;
  margin-bottom: 8px;
  color: #495057;
}

.form-control {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-control:focus {
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
  outline: none;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0069d9;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 123, 255, 0.2);
}

.btn-block {
  width: 100%;
}

/* 加载指示器 */
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 错误消息 */
.error-message {
  color: #721c24;
  background-color: #f8d7da;
  border-left: 4px solid #f5c6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

/* 成功消息 */
.success-message {
  color: #155724;
  background-color: #d4edda;
  border-left: 4px solid #c3e6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
</style>